package com.liangsui.mss.utils;

import com.liangsui.mss.constants.Constants;
import com.liangsui.mss.constants.HttpStatus;
import com.liangsui.mss.domain.SimpleUser;
import com.liangsui.mss.domain.User;
import com.liangsui.mss.exception.AlertException;
import com.liangsui.mss.vo.ActiverUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import java.util.List;

/**
 * ShiroSecurityUtils
 *
 * @author zhangjiawei
 * @email 1533167396@qq.com
 * @date 2022/12/4 20:37
 */
@Slf4j
public class ShiroSecurityUtils {

    /***
     * @Description: 得到当前登陆的用户对象的ActiveUser
     */
    public static ActiverUser getCurrentActiveUser() {
        Subject subject = SecurityUtils.getSubject();
        ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
        log.info("获取当前登录的用户:{ActiveUser}" + activerUser);
        return activerUser;
    }

    /***
     * @Description: 得到当前登陆的用户对象User
     */
    public static User getCurrentUser() {
        final User user = getCurrentActiveUser().getUser();
        if (user == null) {
            throw new AlertException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
        }
        if (user != null) {
            return getCurrentActiveUser().getUser();
        }
        throw new AlertException(HttpStatus.UNAUTHORIZED, "找不到当前登录的信息");
    }

    /***
     * @Description: 得到当前登陆的用户对象SimpleUser
     */
    public static SimpleUser getCurrentSimpleUser() {
        User user = getCurrentActiveUser().getUser();
        if (user == null) {
            throw new AlertException(HttpStatus.UNAUTHORIZED, "当前登录状态过期");
        }
        return new SimpleUser(user.getUserId(), user.getUserName());
    }

    /***
     * @Description: 得到当前登陆的用户名称
     */
    public static String getCurrentUserName() {
        return getCurrentActiveUser().getUser().getUserName();
    }

    /***
     * @Description: 得到当前登陆对象的角色编码
     */
    public static List<String> getCurrentUserRoles() {
        return getCurrentActiveUser().getRoles();
    }


    /***
     * @Description: 得到当前登陆对象的权限编码
     */
    public static List<String> getCurrentUserPermissions() {
        return getCurrentActiveUser().getPermissions();
    }

    /***
     * @Description: 判断当前用户是否是超管
     */
    public static boolean isAdmin() {
        return getCurrentUser().getUserType().equals(Constants.USER_ADMIN);
    }

}
